android如何將listview項目發送到另一個活動 (android How to send listview item to another activity)


問題描述

android如何將listview項目發送到另一個活動 (android How to send listview item to another activity)

I am trying to send row item from list view to another activity but maybe I do something wrong.

I made one app for food. And I want when the user click to "First Activity" the list item from this listview to be send to "Second Activity" and when the user click to "Add to cart" the listview item go to Cart.class

But when I click to "Add to cart" the Activity is send me tо Cart.class but there have nothing.

In cart.xml I have listvew.

Sorry for my bad english

Thanks in advance.

First Activity.

public class UnderCal extends Activity {


String classes[] = {"Grilled chicken","Asiago","Spicy"};


int[] meal = new int[]{
        R.drawable.grilledchicken,
        R.drawable.asiago,
        R.drawable.spicy


};

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);


    setContentView(R.layout.under_menu);



   final List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

    for(int i=0;i<3;i++){
        HashMap<String, String> hm = new HashMap<String,String>();

        hm.put("food", Integer.toString(meal[i]));

        hm.put("txt", "" + classes[i]);

        aList.add(hm);

    }


    // Keys used in Hashmap
    String[] from = {"food","arrow","txt"};

    // Ids of views in listview_layout
    int[] to = { R.id.food,R.id.arrow,R.id.txt};

    // Instantiating an adapter to store each items
    // R.layout.listview_layout defines the layout of each item
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.list_layout, from, to);

    // Getting a reference to listview of main.xml layout file
    final ListView listView = ( ListView ) findViewById(R.id.mylist);

    // Setting the adapter to the listView
    listView.setAdapter(adapter);



    listView.setDivider(new ColorDrawable(0xffffffff));
    listView.setDividerHeight(1);


    listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id)
        {


            if (position == 0)
            {
                Intent intent = new Intent(UnderCal.this,GrilledChicken.class);

               // intent.putExtra("get", aList.get(position));


              String result = (String) listView.getItemAtPosition(position).toString();
              intent.putExtra("get",result);
              startActivity(intent);

                overridePendingTransition(R.anim.animation3, R.anim.animation4);




    }


    }
    });

}

Second Activity.

public class GrilledChicken extends Activity {


Button butadd;


//HashMap<String, String> hm;

String  list;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);


    setContentView(R.layout.grilled_chicken);


    //hash
   // hm =(HashMap<String, String>)getIntent().getSerializableExtra("get");


    Bundle extras = getIntent().getExtras();
    list = extras.getString("get");     

    butadd=(Button) findViewById(R.id.butadd);


    butadd.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // TODO Auto‑generated method stub


            Intent intent = new Intent(GrilledChicken.this,Cart.class);
            // intent.putExtra("hm",hm);

            intent.putExtra("list",list);


            intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
            startActivity(intent);

            }


    });

Cart.class

public class Cart extends Activity {


protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    //Remove title bar
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);


    setContentView(R.layout.cart);


    Bundle extras = getIntent().getExtras();
    String pos = extras.getInt("list");

     }
 }

參考解法

方法 1:

For get item from your listview you have to write following code.

String item = food.get(position).toString();

Write this on your Itemclick method

方法 2:

Put the following code in your Cart.class

Bundle extras = getIntent().getExtras();
 String   list_data = extras.getString("list"); 

Now list_data contains the data.

There is another way through which you can do the task also.

Create a separate Global Class

Global.class

public class Globalclass {
    public static String list_data;

}

And then in your FirstActivity replace the following

intent.putExtra("get",result);

with

Globalclass.list_data=result;

Now you can access the list_dataanywhere like the following

String data=Globalclass.list_data;

方法 3:

Try this once I hope this will help you. 

First of all do this in YourFirstActivity

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getActivity(), YourSecondActivity.class);
            YourModel yourModel = (YourModel) parent.getItemAtPosition(position);
            intent.putExtra("yourModel", yourModel);
            startActivity(intent);
        }
    });

At another Activity do this.

YourModel yourModel= (YourModel) getIntent().getSerializableExtra("yourModel");

From yourModel object you will get all the data of your ListView selected item of YourFirstActivity to YourSecondActivity.

方法 4:

Multiple Send ListView Item:‑

 ArrayList<String>checked11 = new ArrayList<String>();
 SparseBooleanArray checked = listView1.getCheckedItemPositions();
 final ArrayList<String> selectedItems = new ArrayList<String>();

 for (int i = 0; i < checked.size(); i++) {
     int position = checked.keyAt(i);
     if (checked.get(i))
         selectedItems.add(checked11.get(position));
 }

 String[] outputStrArr = new String[selectedItems.size()];

  for (int i = 0; i < selectedItems.size(); i++) {
       outputStrArr[i] = selectedItems.get(i);
  }

use Bunddle :

 Bundle bundle = new Bundle();
 Intent intent = new Intent(getApplicationContext(),
                                    OtherActivity.class);
 bundle.putStringArray("selectedItems", outputStrArr);
 intent.putExtra("screen2", "sub");
 intent.putExtras(bundle);
 intent.putExtra(EXTRA_RESPONSE, selected);
 startActivity(intent);

(by cross_fireSavan Kachhiya PatelSpring BreakerJaydip UmaretiyaPranav Moyal)

參考文件

  1. android How to send listview item to another activity (CC BY‑SA 3.0/4.0)

#listview #Android #listitem






相關問題

ListView中的序列號列 (Serial number Column in ListView)

狀態列表可繪製在預蜂窩版本上無法正常工作 (State list drawable not working properly on pre-honeycomb versions)

我可以減少列表視圖的執行時間嗎? (Can i reduce execution time of listview?)

ListView Windows 8 多個索引 (ListView Windows 8 multiple indexes)

如何通過單擊歌曲列表來播放歌曲 (How to play the song by clicking the lists of song)

Thuộc tính chi tiết trong ListView không hiển thị (Details property in ListView not displaying)

如何從 DataModel 動態訪問數據以獲取 Blackberry 10 中的可折疊列表 (How to access data dynamically from DataModel for collapsible list in Blackberry 10)

android如何將listview項目發送到另一個活動 (android How to send listview item to another activity)

實現 RecyclerView (Implementing RecyclerView)

如何刪除列表視圖底部的多餘空間? (How can I remove extraspace in listview bottom?)

ListViewItem ItemSelectionChangedEvent 觸發 4 次 [e.Selected 觸發兩次] 導致 Win32 異常未處理 (ListViewItem ItemSelectionChangedEvent Fires 4 times [e.Selected fires twice] leads to Win32 Exception Unhandled)

Kivy:如何使用 RecycleView 在 Kivy 中顯示具有可變行的列表? (Kivy: how to display a list with variable rows in Kivy with a RecycleView?)







留言討論